using System.Collections;
using System.Collections.ObjectModel;
using System.Windows;
using HandyControl.Controls;
using Microsoft.Xaml.Behaviors;
using System.Reflection;
using System.Windows.Controls;

namespace MyToDo.Extensions
{
    /// <summary>
    /// CheckComboBox的扩展类，提供附加属性以支持选中项的双向绑定
    /// </summary>
    public static class CheckComboBoxExtensions
    {
        #region SelectedItems 附加属性
        /// <summary>
        /// SelectedItems附加属性的依赖属性标识符
        /// </summary>
        public static readonly DependencyProperty SelectedItemsProperty = 
            DependencyProperty.RegisterAttached(
                "SelectedItems", 
                typeof(IList), 
                typeof(CheckComboBoxExtensions), 
                new FrameworkPropertyMetadata(
                    null, 
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
                    OnSelectedItemsChanged
                )
            );

        /// <summary>
        /// 获取SelectedItems附加属性的值
        /// </summary>
        public static IList GetSelectedItems(DependencyObject obj)
        {
            return (IList)obj.GetValue(SelectedItemsProperty);
        }

        /// <summary>
        /// 设置SelectedItems附加属性的值
        /// </summary>
        public static void SetSelectedItems(DependencyObject obj, IList value)
        {
            obj.SetValue(SelectedItemsProperty, value);
        }

        /// <summary>
        /// SelectedItems附加属性值变化时的回调函数
        /// 当ViewModel中的选中项集合变化时，同步到CheckComboBox
        /// </summary>
        private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is CheckComboBox checkComboBox)
            {
                // 确保CheckComboBox处于多选模式
                checkComboBox.SelectionMode = SelectionMode.Multiple;
                
                // 获取CheckComboBox的内部_isInternalAction字段，避免循环更新
                var isInternalActionField = typeof(CheckComboBox).GetField("_isInternalAction", 
                    BindingFlags.NonPublic | BindingFlags.Instance);
                
                if (isInternalActionField != null && (bool)isInternalActionField.GetValue(checkComboBox))
                    return;
                
                // 设置内部标记以避免循环更新
                if (isInternalActionField != null)
                    isInternalActionField.SetValue(checkComboBox, true);
                
                try
                {
                    // 清除现有的选中项
                    checkComboBox.SelectedItems.Clear();
                    
                    // 添加新的选中项
                    if (e.NewValue is IList newSelectedItems && newSelectedItems.Count > 0)
                    {
                        foreach (var item in newSelectedItems)
                        {
                            checkComboBox.SelectedItems.Add(item);
                        }
                    }
                }
                finally
                {
                    // 清除内部更新标记
                    if (isInternalActionField != null)
                        isInternalActionField.SetValue(checkComboBox, false);
                }
            }
        }
        #endregion
    }

    /// <summary>
    /// CheckComboBox的行为类，用于监听控件的选中项变化并同步到附加属性
    /// </summary>
    public class CheckComboBoxBehavior : Behavior<CheckComboBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            // 确保CheckComboBox处于多选模式
            AssociatedObject.SelectionMode = SelectionMode.Multiple;
            // 监听SelectionChanged事件
            AssociatedObject.SelectionChanged += OnSelectionChanged;
            
            // 初始同步 - 将控件的当前选中项同步到附加属性
            SyncControlToProperty();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            // 取消监听SelectionChanged事件
            AssociatedObject.SelectionChanged -= OnSelectionChanged;
        }

        /// <summary>
        /// 处理CheckComboBox的选中项变化事件
        /// </summary>
        private void OnSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 获取CheckComboBox的内部_isInternalAction字段，避免循环更新
            var isInternalActionField = typeof(CheckComboBox).GetField("_isInternalAction", 
                BindingFlags.NonPublic | BindingFlags.Instance);
            
            if (isInternalActionField != null && (bool)isInternalActionField.GetValue(AssociatedObject))
                return;
            
            // 同步控件的选中项到附加属性
            SyncControlToProperty();
        }

        /// <summary>
        /// 将控件的选中项同步到附加属性
        /// </summary>
        private void SyncControlToProperty()
        {
            // 创建一个新的ObservableCollection来存储选中项
            var selectedItems = new ObservableCollection<object>();
            
            // 获取CheckComboBox的内部_isInternalAction字段
            var isInternalActionField = typeof(CheckComboBox).GetField("_isInternalAction", 
                BindingFlags.NonPublic | BindingFlags.Instance);
            
            // 设置内部标记以避免循环更新
            if (isInternalActionField != null)
                isInternalActionField.SetValue(AssociatedObject, true);
            
            try
            {
                // 将CheckComboBox中的选中项添加到新集合中
                foreach (var item in AssociatedObject.SelectedItems)
                {
                    selectedItems.Add(item);
                }
                
                // 设置附加属性的值
                CheckComboBoxExtensions.SetSelectedItems(AssociatedObject, selectedItems);
            }
            finally
            {
                // 清除内部更新标记
                if (isInternalActionField != null)
                    isInternalActionField.SetValue(AssociatedObject, false);
            }
        }
    }
}